package com.huaxindata.im.main.contactview.friend;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxindata.common.util.DialogUtil;
import com.huaxindata.common.util.ToastUtil;
import com.huaxindata.common.view.ToggleButton;
import com.huaxindata.im.R;
import com.huaxindata.im.R2;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.http.RetrofitClient;
import com.huaxindata.im.main.addFriend.AddFriendActivity;
import com.huaxindata.im.main.chat.ConversationManager;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.model.contact.UserMessage;
import com.huaxindata.im.model.db.MessageStore;
import com.huaxindata.im.util.SharePreferenceUtil;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 本类主要用于显示好友的资料，并提供以下功能
 * 通过Intent将联系人数据传送过来
 * 1、设置消息免打扰，即聊天的时候消息来了不震动也不通知
 * 2、删除聊天消息记录
 * 3、解除好友关系
 */
public class FriendInfoActivity extends BaseActivity {

    @BindView(R2.id.friend_info_toolbar)
    Toolbar         mToolbar;
    @BindView(R2.id.friend_info_icon)
    AvatarImageView mFriendInfoIcon;
    @BindView(R2.id.friend_info_title)
    TextView        mFriendInfoTitle;
    @BindView(R2.id.friend_info_nickname)
    TextView        mFriendInfoNickname;
    @BindView(R2.id.friend_info_phone)
    TextView        mFriendInfoPhone;
    @BindView(R2.id.friend_info_description)
    TextView        mFriendInfoDescription;
    @BindView(R2.id.friend_info_message_ignore)
    ToggleButton    mFriendInfoMessageIgnore;
    @BindView(R2.id.friend_info_ignore)
    RelativeLayout  mFriendInfoIgnore;
    @BindView(R2.id.friend_info_clear_record)
    RelativeLayout  mFriendInfoClearRecord;
    @BindView(R2.id.relieve_friend_btn)
    Button          mRelieveFriendBtn;
    @BindView(R2.id.friend_add_btn)
    Button          mFriendAddBtn;
    @BindView(R2.id.user_name_tv)
    TextView        mUserNameTv;


    private String             mClientId;
    private boolean            isDelete;
    private HxAvatarImageGlide mImageInstance;
    private UserMessage        mUserMessage;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_friend_info;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        mClientId = extras.getString(ImConstants.CLIENT_ID);
    }


    @Override
    public void initView() {
        setSupportActionBar(mToolbar);
        mToolbar.setTitle("个人信息");

    }

    @Override
    public void initData() {
        mImageInstance = HxAvatarImageGlide.getInstance();

    }

    @Override
    protected void requestData() {
        updateLoadStatus(LOADING);
        if (TextUtils.isEmpty(mClientId)) {
            updateLoadStatus(LOAD_ERROR);
            return;
        }
        Call<UserMessage> call = RetrofitClient.getHttpApi().getUserById(mClientId);
        autoClose(call);
        call.enqueue(new Callback<UserMessage>() {
            @Override
            public void onResponse(Call<UserMessage> call, Response<UserMessage> response) {
                if (response.isSuccessful()) {
                    updateLoadStatus(LOAD_SUCCESS);
                    mUserMessage = response.body();
                    bindData(mUserMessage);
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<UserMessage> call, Throwable t) {
                updateLoadStatus(LOAD_ERROR);
            }
        });

    }

    /**
     * 绑定数据
     *
     * @param userMessage
     */
    private void bindData(UserMessage userMessage) {
        mFriendInfoNickname.setText(userMessage.getNickName());
        mUserNameTv.setText(userMessage.getNickName());
        mFriendInfoTitle.setText(userMessage.getTitle());
        mFriendInfoNickname.setEnabled(false);
        mFriendInfoPhone.setText(userMessage.getPhone());
        mImageInstance.setHeadImage(this, userMessage.getImg(), userMessage.getNickName(), mFriendInfoIcon);
        if (ContactManager.isFriend(mClientId)) { //是好友
            //是否解除好友
            mRelieveFriendBtn.setVisibility(View.VISIBLE);
            //添加好友
            mFriendAddBtn.setVisibility(View.GONE);
        } else {
            mRelieveFriendBtn.setVisibility(View.GONE);
            mFriendAddBtn.setVisibility(View.VISIBLE);
        }
        mFriendInfoMessageIgnore.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
                SharePreferenceUtil.setBoolean(FriendInfoActivity.this, "friend_" + mClientId, on);
            }
        });
        if (SharePreferenceUtil.getBoolean(this, "friend_" + mClientId, false)) {
            mFriendInfoMessageIgnore.setToggleOn();
        } else {
            mFriendInfoMessageIgnore.setToggleOff();
        }
    }

    /**
     * 清除聊天记录
     *
     * @param v
     */
    public void clearRecord(View v) {
        final Dialog dialog = DialogUtil.getConfirmDialog(this, null, "是否清空记录?", "确认", "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MessageStore.deleteFriendMsg(mClientId, UserManager.getClientId());//删除与此id相关的所有聊天记录
                dialog.dismiss();
                Toast toast = Toast.makeText(FriendInfoActivity.this, "记录已清空", Toast.LENGTH_SHORT);
                toast.show();
                isDelete = true;
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create();
        dialog.show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }


    private void deleteFriend() {
        final Dialog dialog = DialogUtil.getConfirmDialog(this, "确认解除好友关系？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Call<String> call = RetrofitClient.getHttpApi().delFriend(UserManager
                        .getClientId(), mClientId);
                call.enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        //删除成功，删除聊天记录，回到主界面
                        mRelieveFriendBtn.setVisibility(View.GONE);
                        MessageStore.deleteFriendMsg(mClientId, UserManager.getClientId());//删除与此id相关的所有聊天记录
                        ConversationManager.sendDeleteFriendMessage(mClientId);
                        ContactManager.removeFriend(mClientId);//从好友列表中删除
                        ToastUtil.showToast(FriendInfoActivity.this, "好友关系已解除");
                        setResult(ImConstants.RESULT_CODE_EXIT);
                        finish();
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        ToastUtil.showToast(FriendInfoActivity.this, "网络异常");
                    }
                });
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    public void finish() {
        if (isDelete) {
            setResult(ImConstants.RESULT_CODE_EXIT);
        }
        super.finish();
    }

    @OnClick(R2.id.relieve_friend_btn)//解除好友
    public void onViewClicked1(View view) {

        deleteFriend();
    }

    @OnClick(R2.id.friend_add_btn)//添加好友
    public void onViewClicked2(View view) {
        Intent intent = new Intent(FriendInfoActivity.this, AddFriendActivity.class);
        intent.putExtra(ImConstants.FUNCTION_ADD_FRIEND, ImConstants.FUNCTION_REQUEST);
        ContactPerson contactPerson = new ContactPerson(mClientId, mUserMessage.getNickName(), mUserMessage.getImg());
        intent.putExtra(ImConstants.CONTACT, contactPerson);
        FriendInfoActivity.this.startActivity(intent);
    }
}
